// 瓦片加载器类 - 负责瓦片的加载、缓存和管理
class TileLoader {
  constructor() {
    this.tileCache = new Map(); // 瓦片缓存
    this.loadingTiles = new Set(); // 正在加载的瓦片
    this.maxCacheSize = 1000; // 最大缓存瓦片数量
  }

  // 获取瓦片URL
  getTileUrl(z, x, y, type = 'tile') {
    const baseUrl = type === 'tile' ? '/api/tiles' : '/api/vector';
    const extension = type === 'tile' ? 'png' : 'json';
    return `${baseUrl}/${z}/${x}/${y}.${extension}`;
  }

  // 加载瓦片图片
  async loadTileImage(z, x, y) {
    const cacheKey = `tile-${z}-${x}-${y}`;
    
    // 检查缓存
    if (this.tileCache.has(cacheKey)) {
      return this.tileCache.get(cacheKey);
    }

    // 检查是否正在加载
    if (this.loadingTiles.has(cacheKey)) {
      return null; // 正在加载中，返回null
    }

    this.loadingTiles.add(cacheKey);

    try {
      const url = this.getTileUrl(z, x, y, 'tile');
      const response = await fetch(url);
      
      if (!response.ok) {
        throw new Error(`Failed to load tile: ${response.status}`);
      }

      const blob = await response.blob();
      const imageUrl = URL.createObjectURL(blob);
      
      // 缓存瓦片
      this.tileCache.set(cacheKey, imageUrl);
      this.cleanupCache();
      
      return imageUrl;
    } catch (error) {
      console.warn(`Failed to load tile z=${z}, x=${x}, y=${y}:`, error);
      return null;
    } finally {
      this.loadingTiles.delete(cacheKey);
    }
  }

  // 加载矢量数据
  async loadVectorData(z, x, y) {
    const cacheKey = `vector-${z}-${x}-${y}`;
    
    // 检查缓存
    if (this.tileCache.has(cacheKey)) {
      return this.tileCache.get(cacheKey);
    }

    // 检查是否正在加载
    if (this.loadingTiles.has(cacheKey)) {
      return null;
    }

    this.loadingTiles.add(cacheKey);

    try {
      const url = this.getTileUrl(z, x, y, 'vector');
      const response = await fetch(url);
      
      if (!response.ok) {
        throw new Error(`Failed to load vector data: ${response.status}`);
      }

      const vectorData = await response.json();
      
      // 缓存矢量数据
      this.tileCache.set(cacheKey, vectorData);
      this.cleanupCache();
      
      return vectorData;
    } catch (error) {
      console.warn(`Failed to load vector data z=${z}, x=${x}, y=${y}:`, error);
      return null;
    } finally {
      this.loadingTiles.delete(cacheKey);
    }
  }

  // 清理缓存
  cleanupCache() {
    if (this.tileCache.size > this.maxCacheSize) {
      // 删除最旧的缓存项
      const keys = Array.from(this.tileCache.keys());
      const keysToDelete = keys.slice(0, this.tileCache.size - this.maxCacheSize);
      
      keysToDelete.forEach(key => {
        const value = this.tileCache.get(key);
        if (typeof value === 'string' && value.startsWith('blob:')) {
          URL.revokeObjectURL(value); // 释放blob URL
        }
        this.tileCache.delete(key);
      });
    }
  }

  // 预加载瓦片
  preloadTiles(visibleTiles) {
    visibleTiles.forEach(tile => {
      const { z, x, y } = tile;
      this.loadTileImage(z, x, y);
      this.loadVectorData(z, x, y);
    });
  }

  // 清除所有缓存
  clearCache() {
    // 释放所有blob URL
    this.tileCache.forEach((value, key) => {
      if (typeof value === 'string' && value.startsWith('blob:')) {
        URL.revokeObjectURL(value);
      }
    });
    
    this.tileCache.clear();
    this.loadingTiles.clear();
  }

  // 获取缓存统计信息
  getCacheStats() {
    return {
      totalCached: this.tileCache.size,
      loading: this.loadingTiles.size,
      maxSize: this.maxCacheSize
    };
  }
}

export default TileLoader;